package com.cvr.project.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.cvr.project.R;
import com.cvr.project.repertory.LViewModelProviders;
import com.cvr.project.utils.DomainManager;
import com.cvr.project.utils.JayCommonUtil;
import com.cvr.project.utils.ToastUtils;
import com.cvr.project.utils.WatermarkManager;
import com.cvr.project.viewmodel.MainViewModel;
import com.gyf.immersionbar.ImmersionBar;
import com.huashi.otg.sdk.HSIDCardInfo;
import com.huashi.otg.sdk.HSLOG;
import com.huashi.otg.sdk.HandlerMsg;
import com.huashi.otg.sdk.HsOtgApi;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HomeActivity extends AppCompatActivity {
    public static String phone = "";
    boolean m_Con = false;

    boolean m_Auto = false;
    long startTime;
    HsOtgApi api = null;
    String filepath = "";
    SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");// 设置日期格式
    int m_ReadIDCardSUCCESS = 0;
    private MainViewModel viewModel;
    private static final String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this).transparentStatusBar().navigationBarColor(R.color.white).statusBarDarkFont(true).init();
        setContentView(R.layout.activity_home);
        DomainManager.init(getApplicationContext());
        

        
        setupUI();
    }

    @Override
    protected void onResume() {
        super.onResume();
        
        // 添加水印
        WatermarkManager.getInstance().addWatermark(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }




    private void setupUI() {
        boolean firstLaunch = DomainManager.getInstance().isFirstLaunch();
        if (firstLaunch){
            DomainManager.getInstance().showDomainConfigDialog(this, new DomainManager.OnDomainConfigListener() {
                @Override
                public void onDomainConfigured(String baseUrl, String h5Url) {
                    init();
                    // 域名配置完成后更新URL显示
                    displayUrlInfo();
                }
            });
        }else {
            init();
        }
    }

    private void init(){
        // 显示URL信息
        displayUrlInfo();
        
        onInitIDCard();
        onConnect();
        onPostHttpEvent();
        findViewById(R.id.btn_card).setOnClickListener(v -> {
            if (!JayCommonUtil.isFastClick()){

                requestPermission(0);
            }
        });
        findViewById(R.id.btn_biometric).setOnClickListener(v -> {
            if (!JayCommonUtil.isFastClick()){

                requestPermission(1);
            }
        });
        findViewById(R.id.btn_camera).setOnClickListener(v -> {
            if (!JayCommonUtil.isFastClick()){

                requestPermission(2);
            }
        });

    }

    /**
     * 显示URL信息
     */
    private void displayUrlInfo() {
        TextView tvApiUrl = findViewById(R.id.tv_api_url);
        TextView tvWebUrl = findViewById(R.id.tv_web_url);
        
        // 获取并显示API URL和WEB URL
        String apiUrl = DomainManager.getInstance().getBaseUrl();
        String webUrl = DomainManager.getInstance().getH5Url();
        
        tvApiUrl.setText(apiUrl);
        tvWebUrl.setText(webUrl);
        

    }
    


    private int typeValue;

    public static boolean validatePhoneNumber(String phoneNumber) {
        String regex = "^1[3-9]\\d{9}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phoneNumber);
        return matcher.matches();
    }

    private void requestPermission(int type) {
        EditText editText = findViewById(R.id.et_phone);
        if (TextUtils.isEmpty(editText.getText())) {
            ToastUtils.showToast(this, "请先输入手机号");
            return;
        }
        if (!validatePhoneNumber(editText.getText().toString().trim())) {
            ToastUtils.showToast(this, "请输入正确格式的手机号");
            return;
        }
        phone = editText.getText().toString().trim();
        typeValue = type;
        if (Build.VERSION.SDK_INT >= 23) {
            ActivityCompat.requestPermissions(this, permissions, 1001);
        } else {
            switch (typeValue) {
                case 0:
                    onOTGEvent();
                    break;
                case 1:
                    startActivity(new Intent(HomeActivity.this, BiometricActivity.class));
                    break;
                case 2:
                    startActivity(new Intent(HomeActivity.this, CameraActivity.class));
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1001) {
            if (isGrantedResult()) {
                switch (typeValue) {
                    case 0:
                        onOTGEvent();
                        break;
                    case 1:
                        startActivity(new Intent(HomeActivity.this, BiometricActivity.class));
                        break;
                    case 2:
                        startActivity(new Intent(HomeActivity.this, CameraActivity.class));
                        break;
                }
            } else {
                ToastUtils.showToast(this, "权限未获取");
            }
        }
    }

    private boolean isGrantedResult(int... grantResults) {
        for (int result : grantResults) {
            if (result == PackageManager.PERMISSION_DENIED) return false;
        }
        return true;
    }

    private void onOTGEvent() {
        if (null != handler && null != loopRunnable) {
            handler.removeCallbacks(loopRunnable);
        }
        if ( null != handler) {
            handler.sendEmptyMessage(10013);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 10013:
                    handler.postDelayed(loopRunnable, 1000);
                    break;
                case 10014:
                    handler.removeMessages(10013);
                    handler.removeCallbacks(loopRunnable);
                    break;
            }
        }
    };

    private final Runnable loopRunnable = () -> {
        onReadCard();
        handler.sendEmptyMessage(10013);
    };

    private void onReadCard() {
        if (!m_Con) {
     //       Toast.makeText(this, "100U未连接", Toast.LENGTH_SHORT).show();
            return;
        }
        startTime = System.currentTimeMillis();
        if (api.Authenticate(200, 200) != 1) {
//            ToastUtils.showToast(this, "卡认证失败,请重新点击识别");
            return;
        }
        HSIDCardInfo ici = new HSIDCardInfo();
        if (api.ReadCard(ici, 200, 1300) == 1) {
            handler.sendEmptyMessage(10014);
            Message msg = Message.obtain();
            msg.obj = ici;
            msg.what = HandlerMsg.READ_SUCCESS;
            h.sendMessage(msg);
        }
    }

    private void onInitIDCard() {
        filepath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/wltlib";// 授权目录
        Log.e("LJFDJ", filepath);
        isFolderExists(filepath);
        // 高版本安卓需要自动申请SD卡读写权限
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (HomeActivity.this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    HomeActivity.this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }
        // android 12
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted, request it
            int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
        }
    }

    private void onPostHttpEvent() {
        viewModel = LViewModelProviders.of(this, MainViewModel.class);
        viewModel.icCardLoginLiveData.observe(this, idCardEntity -> {
            onDismissProgress();
            WebViewActivity.getInstance(HomeActivity.this, idCardEntity.getToken_info().getToken());
            finish();
        });
        viewModel.errorTipLiveData.observe(this, s -> {
            onDismissProgress();
            showNormalAlertDialog(s);
        });
    }

    private void onConnect() {
        if (m_Con) {
            m_Auto = false;
            SystemClock.sleep(1500);
            if (api != null) {
                api.unInit();
                api = null;
            }
            m_Con = false;
//            Toast.makeText(this, "断开连接成功", Toast.LENGTH_SHORT).show();
        } else {
            if (api == null) {
                api = new HsOtgApi(h, HomeActivity.this);
            }
            int ret = api.init();// 因为第一次需要点击授权，第一次点击时候的返回是-1,我利用了广播接受到授权后用handler发送消息
            HSLOG.m_Addlog = false;
            if (ret == 1) {
         //       Toast.makeText(this, "连接成功", Toast.LENGTH_SHORT).show();
                m_Con = true;
            } else {
//                Toast.makeText(this, "连接失败", Toast.LENGTH_SHORT).show();
                m_Con = false;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        
        // 移除水印
        WatermarkManager.getInstance().removeWatermark(this);
        
        onDismissProgress();
        if (m_Auto) {
            m_Auto = false;
            SystemClock.sleep(1500);
        }
        if (api == null) {
            return;
        }
        api.unInit();
        if (null != loopRunnable) {
            handler.removeCallbacks(loopRunnable);
        }
    }

    /**
     * 指纹 指位代码
     *
     * @param FPcode
     * @return
     */
    String GetFPcode(int FPcode) {
        switch (FPcode) {
            case 11:
                return "右手拇指";
            case 12:
                return "右手食指";
            case 13:
                return "右手中指";
            case 14:
                return "右手环指";
            case 15:
                return "右手小指";
            case 16:
                return "左手拇指";
            case 17:
                return "左手食指";
            case 18:
                return "左手中指";
            case 19:
                return "左手环指";
            case 20:
                return "左手小指";
            case 97:
                return "右手不确定指位";
            case 98:
                return "左手不确定指位";
            case 99:
                return "其他不确定指位";
            default:
                return "未知";
        }
    }

    boolean isFolderExists(String strFolder) {
        File file = new File(strFolder);
        if (!file.exists()) {
            if (file.mkdir()) {
                return true;
            } else
                return false;
        }
        return true;
    }

    @SuppressLint("HandlerLeak")
    Handler h = new Handler() {
        @SuppressLint({"DefaultLocale", "SetTextI18n"})
        public void handleMessage(Message msg) {
            if (msg.what == 99 || msg.what == 100) {
//                statu.setText((String) msg.obj);
                m_Con = false;
            }
            // 第一次授权时候的判断是利用handler判断，授权过后就不用这个判断了
            if (msg.what == HandlerMsg.CONNECT_SUCCESS) {
//                statu.setText("连接成功" + api.GetSAMID());
                m_Con = true;
                //sam.setText(api.GetSAMID());
            }
            if (msg.what == HandlerMsg.CONNECT_ERROR) {
//                statu.setText("连接失败");
            }
            if (msg.what == HandlerMsg.READ_ERROR) {
//                statu.setText("请放卡...");
            }
            if (msg.what == HandlerMsg.READ_SUCCESS) {

                HSIDCardInfo ic = (HSIDCardInfo) msg.obj;
                byte[] fp = new byte[1024];
                fp = ic.getFpDate();
                String m_FristPFInfo = "";
                String m_SecondPFInfo = "";

                if (fp[4] == (byte) 0x01) {
                    m_FristPFInfo = String.format(
                            "指纹  信息：第一枚指纹注册成功。指位：%s。指纹质量：%d \n",
                            GetFPcode(fp[5]), fp[6]);
                } else {
                    m_FristPFInfo = "身份证无指纹 \n";
                }
                if (fp[512 + 4] == (byte) 0x01) {
                    m_SecondPFInfo = String.format(
                            "指纹  信息：第二枚指纹注册成功。指位：%s。指纹质量：%d \n",
                            GetFPcode(fp[512 + 5]), fp[512 + 6]);
                } else {
                    m_SecondPFInfo = "身份证无指纹 \n";
                }
                if (ic.getcertType() == " ") {
//                    tv_info.setText("证件类型：身份证\n" + "姓名：" + ic.getPeopleName()
//                            + "\n" + "性别：" + ic.getSex() + "\n" + "民族："
//                            + ic.getPeople() + "\n" + "出生日期："
//                            + df.format(ic.getBirthDay()) + "\n" + "地址："
//                            + ic.getAddr() + "\n" + "身份号码：" + ic.getIDCard()
//                            + "\n" + "签发机关：" + ic.getDepartment() + "\n"
//                            + "有效期限：" + ic.getStrartDate() + "-"
//                            + ic.getEndDate() + "\n" + m_FristPFInfo + "\n"
//                            + m_SecondPFInfo);
                } else {
                    if (ic.getcertType() == "J") {
//                        tv_info.setText("证件类型：港澳台居住证（J）\n" + "姓名："
//                                + ic.getPeopleName() + "\n" + "性别："
//                                + ic.getSex() + "\n" + "签发次数："
//                                + ic.getissuesNum() + "\n" + "通行证号码："
//                                + ic.getPassCheckID() + "\n" + "出生日期："
//                                + df.format(ic.getBirthDay()) + "\n" + "地址："
//                                + ic.getAddr() + "\n" + "身份号码："
//                                + ic.getIDCard() + "\n" + "签发机关："
//                                + ic.getDepartment() + "\n" + "有效期限："
//                                + ic.getStrartDate() + "-" + ic.getEndDate()
//                                + "\n" + m_FristPFInfo + "\n" + m_SecondPFInfo);
                    } else {
                        if (ic.getcertType() == "I") {
//                            tv_info.setText("证件类型：外国人永久居留证（I）\n" + "英文名称："
//                                    + ic.getPeopleName() + "\n" + "中文名称："
//                                    + ic.getstrChineseName() + "\n" + "性别："
//                                    + ic.getSex() + "\n" + "永久居留证号："
//                                    + ic.getIDCard() + "\n" + "国籍："
//                                    + ic.getstrNationCode() + "\n" + "出生日期："
//                                    + df.format(ic.getBirthDay()) + "\n"
//                                    + "证件版本号：" + ic.getstrCertVer() + "\n"
//                                    + "申请受理机关：" + ic.getDepartment() + "\n"
//                                    + "有效期限：" + ic.getStrartDate() + "-"
//                                    + ic.getEndDate() + "\n" + m_FristPFInfo
//                                    + "\n" + m_SecondPFInfo);
                        } else {
                            if (ic.getcertType() == "Y") {
//                                tv_info.setText("证件类型：外国人永久居留证（Y）\n" + "英文名称："
//                                        + ic.getPeopleName() + ic.getStandbyEName() + "\n" + "中文名称："
//                                        + ic.getstrChineseName() + "\n" + "性别："
//                                        + ic.getSex() + "\n" + "永久居留证号："
//                                        + ic.getIDCard() + "\n" + "国籍："
//                                        + ic.getstrNationCode() + "\n" + "出生日期："
//                                        + df.format(ic.getBirthDay()) + "\n"
//                                        + "签发次数：" + ic.getissuesNum() + "\n"
//                                        + "旧版ID号：" + ic.getOldIDCardNumber() + "\n"
//                                        + "有效期限：" + ic.getStrartDate() + "-"
//                                        + ic.getEndDate() + "\n" + m_FristPFInfo
//                                        + "\n" + m_SecondPFInfo);
                            }
                        }
                    }

                }
                try {
                    byte[] bmpBuf = new byte[102 * 126 * 3 + 54 + 126 * 2]; // 照片头像bmp数据
                    String bmpPath = filepath + "/zp.bmp"; // 照片头像保存路径
                    int ret = api.unpack(ic.getwltdata(), bmpBuf, "");
                    if (ret != 1) {// 解码失败
//                        statu.setText("头像解码失败");
                        return;
                    }

                    Bitmap bitmap = BitmapFactory.decodeByteArray(bmpBuf, 0,
                            bmpBuf.length);
//                    iv_photo.setImageBitmap(bitmap); // 显示头像
                    //////////////////////////////////////////////////////////////////////////////////////
                    // 生成证件正反面，需要给filepath授权写权限
                  /* try {
                       // GetImg.ShowBmp(ic, MainActivity.this, 1, filepath,bitmap);
                        iv_photo.setImageBitmap(GetImg.ShowBmp(ic, MainActivity.this, 1, filepath,bitmap)); // 显示正反面
                    } catch (IOException e) {
                        e.printStackTrace();
                    }*/
                    //////////////////////////////////////////////////////////////////////////////////////
                    if (!m_Auto) {
                        startTime = System.currentTimeMillis() - startTime;
//                        statu.setText("读卡成功,用时：" + startTime);
                        showLoading();
                        viewModel.icCardLogin(Objects.equals(ic.getcertType(), "J") ? ic.getissuesNum() : ic.getIDCard(), HomeActivity.phone);
                    } else {
//                        statu.setText("读卡成功");
                        m_ReadIDCardSUCCESS++;
//                        tv_Log.setText("成功次数:" + m_ReadIDCardSUCCESS);
                        showLoading();
                        viewModel.icCardLogin(Objects.equals(ic.getcertType(), "J") ? ic.getissuesNum() : ic.getIDCard(), HomeActivity.phone);
                    }
                } catch (Exception e) {
                    showNormalAlertDialog("头像解码失败");
                }
            }
        }
    };
    private ProgressDialog progressDialog;

    private void showLoading() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("上传中，请稍等...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
    }

    private void onDismissProgress() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    private void showNormalAlertDialog(String tip) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setIcon(R.mipmap.ic_launcher)
                .setTitle("提示")
                .setMessage(tip)
                .setPositiveButton("确定", (dialog, which) -> dialog.dismiss());
        builder.create().show();
    }
    
    /**
     * 显示完整性检查失败对话框
     */
    private void showIntegrityFailedDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("安全警告");
        builder.setMessage("检测到应用可能被篡改或运行在不安全的环境中。\n\n" +
                "为了保护您的数据安全，应用将退出。\n\n" +
                "请从官方渠道重新下载安装应用。");
        builder.setCancelable(false);
        
        builder.setPositiveButton("退出", (dialog, which) -> {
            finish();
            System.exit(0);
        });
        
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    

}
